import React, { useState, useEffect } from "react";
import { Table, Button, Select, message } from "antd";
import axios from "axios";
import dayjs from "dayjs";
import { CSVLink } from "react-csv";

const OrderManagement = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState("全部");

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/api/orders", {
        params: { status: statusFilter },
      });
      setOrders(response.data);
    } catch (error) {
      console.error("Error fetching orders:", error);
      message.error("获取订单列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, [statusFilter]);

  const handleUpdateStatus = async (id, newStatus) => {
    try {
      await axios.put(`http://localhost:5000/api/orders/${id}`, { status: newStatus });
      setOrders(orders.map((order) => (order.id === id ? { ...order, status: newStatus } : order)));
      message.success("订单状态更新成功");
    } catch (error) {
      console.error("Error updating order:", error);
      message.error("更新订单状态失败");
    }
  };

  const columns = [
    { title: "订单号", dataIndex: "order_number", key: "order_number" },
    { title: "用户名", dataIndex: "username", key: "username" },
    { title: "金额", dataIndex: "amount", key: "amount" },
    { title: "状态", dataIndex: "status", key: "status" },
    { title: "订单时间", dataIndex: "order_time", key: "order_time", render: (text) => dayjs(text).format("YYYY-MM-DD HH:mm:ss") },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Select
          value={record.status}
          onChange={(value) => handleUpdateStatus(record.id, value)}
          style={{ width: 120 }}
        >
          <Select.Option value="未支付">未支付</Select.Option>
          <Select.Option value="已支付">已支付</Select.Option>
        </Select>
      ),
    },
  ];

  const csvData = orders.map((order) => ({
    order_number: order.order_number,
    username: order.username,
    amount: order.amount,
    status: order.status,
    order_time: dayjs(order.order_time).format("YYYY-MM-DD HH:mm:ss"),
  }));

  return (
    <div style={{ padding: "24px" }}>
      <div style={{ marginBottom: "24px", display: "flex", justifyContent: "space-between" }}>
        <Select
          value={statusFilter}
          onChange={setStatusFilter}
          style={{ width: 200 }}
        >
          <Select.Option value="全部">全部</Select.Option>
          <Select.Option value="未支付">未支付</Select.Option>
          <Select.Option value="已支付">已支付</Select.Option>
        </Select>
        <CSVLink data={csvData} filename={`orders-${dayjs().format("YYYYMMDD")}.csv`}>
          <div style={{  display: "flex", justifyContent: "space-between",alignItems:'center' }}>
          <Button type="primary">导出订单</Button>
          </div>
        </CSVLink>
      </div>
      <Table
        columns={columns}
        dataSource={orders}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
    </div>
  );
};

export default OrderManagement;